﻿using BLL.Basis;
using Entity;
using Newtonsoft.Json;
using SysFrameWork;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;
using Newtonsoft.Json.Linq;

namespace BLL
{
    /// <summary>
    /// 自动执行任务方法类
    /// </summary>
    public class AutoTaskBLL
    {
        TxtLogHelper txt;
        SysFrameWork.SystemBLL sysBLL ;
        HttpAgreement http;
        public AutoTaskBLL()
        {
            txt = new TxtLogHelper();
            sysBLL = new SysFrameWork.SystemBLL();
            http = new HttpAgreement();
        }
        //public void AutoTask()
        public ReturnResult AutoTask()

        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                rsl = sysBLL.getParameterByCode("AutoTask");
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            txt.AddLogMsg(string.Format("成功获取自动执行任务，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
            return rsl;
        }

        /// <summary>
        /// 人员接口同步执行方法(自动任务)
        /// </summary>
        public void Auto_User()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
              txt.AddLogMsg("人员同步开始执行");
            SysFrameWork.UserBLL userBLL=new SysFrameWork.UserBLL();
            rsl = userBLL.SyncUserData(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("人员同步任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        public void Auto_Dept()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("部门同步开始执行");
                SysFrameWork.UserBLL userBLL = new SysFrameWork.UserBLL();
                rsl = userBLL.SyncDept(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("部门同步任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 收发类型
        /// </summary>
        public void Auto_ShouFa()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("收发类型数据同步");
                rsl = sysBLL.SyncShouFa(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("收发类型数据同步程序执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 存货数据同步
        /// </summary>
        public void auto_Product()
        {
            ReturnResult rsl = new ReturnResult();
            bool ischanage = false;
            try
            {
                txt.AddLogMsg("存货档案同步开始执行");
                string date = GetSysFile("SyncProduct");
                if (string.IsNullOrWhiteSpace(date) || DateTime.Parse(date) < DateTime.Now)
                {
                    ProductInfoBLL venBLL = new ProductInfoBLL();
                    rsl = venBLL.SyncInventory(true);
                    ischanage = true;
                }
            
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            #region 记录下一次更新时间
            if (ischanage)
            {
                string filePath = string.Empty;
                string ExcelPathFolder = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "sysLog";
                filePath = System.IO.Path.Combine(ExcelPathFolder, "SyncProduct.txt");
                FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                StreamWriter sr = new StreamWriter(fs);
                string nDate = string.Format("{0} 01:00:00", DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
                sr.Write(nDate);//开始写入值
                sr.Close();
                fs.Close();
            }
            #endregion

            txt.AddLogMsg(string.Format("存货档案同步任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
     
        /// <summary>
        /// 仓库同步
        /// </summary>
        public void auto_WareHouse()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("仓库数据同步开始执行");
                WareHouseBLL wareBLL = new WareHouseBLL();
                rsl = wareBLL.SyncWareHouse(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("仓库数据同步任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 货位信息同步方法
        /// </summary>
         public void auto_WarePosition()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("货位数据同步开始执行");
                WareHouseBLL wareBLL = new WareHouseBLL();
                rsl = wareBLL.SyncWarehousePosition(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("货位数据同步任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 计量单位数据同步方法
        /// </summary>
        public void auto_UnitInfo()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("计量单位同步开始执行");
                ProductInfoBLL venBLL = new ProductInfoBLL();
                rsl = venBLL.SyncProductUnit(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("计量单位任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 客户信息
        /// </summary>
        public void auto_customer()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("客户数据同步开始执行");
                CustomBLL cuBLL = new CustomBLL();
                rsl = cuBLL.SyncCustom("Cu", true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("客户数据同步任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 供应商同步
        /// </summary>
        public void auto_Supplier()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("供方数据同步开始执行");
                CustomBLL cuBLL = new CustomBLL();
                rsl = cuBLL.SyncCustom("Sp", true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("供方数据同步任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
     
    
        /// <summary>
        /// 清除登录日志
        /// </summary>
        public void ClearSSORecord()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("清除客户端登录日志开始执行");
                rsl = sysBLL.ClearSSORecord();
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("清除客户端登录日志任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 存货数据自由项数据同步方法
        /// </summary>
        public void SyncProductCommonData()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("存货数据自由项数据同步方法开始执行");
                ProductInfoBLL proBLL = new ProductInfoBLL();
                rsl = proBLL.SyncProductCommonData(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("存货数据自由项数据同步方法任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }
        /// <summary>
        /// 存货数据自由项档案同步方法
        /// </summary>
        public void SyncProductDefCommonData()
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                txt.AddLogMsg("自定义项档案同步方法开始执行");
                ProductInfoBLL proBLL = new ProductInfoBLL();
                rsl = proBLL.SyncProductDefCommonData(true);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            txt.AddLogMsg(string.Format("自定义项档案同步方法任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }


        /// <summary>
        /// 自动更新token
        /// </summary>
        public void auto_token(string isauto=null)
        {
            ReturnResult rsl = new ReturnResult();
            bool ischanage = false;
            try
            {
                txt.AddLogMsg("更新token开始执行");
                string date = GetSysFile("TokenEnd");  //token失效日期
                //如果当前日期>失效日期    或者    不是自动执行（即入库失败时调用）     更新token
                if ( (string.IsNullOrWhiteSpace(date) || DateTime.Parse(date) < DateTime.Now) || !string.IsNullOrWhiteSpace(isauto) )
                {
                    #region 更新token
                    var msg = http.Get(ConfigReader.Reader["reUrl"], "", "get");
                    var msgObj = JsonConvert.DeserializeObject<JObject>(msg); 
                    var res = msgObj["result"];
                    var newToken = res["access_token"];

                    string filePath = string.Empty;
                    string ExcelPathFolder = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "sysLog";
                    filePath = System.IO.Path.Combine(ExcelPathFolder, "OpenToken.txt");
                    FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                    StreamWriter sr = new StreamWriter(fs);
                    string nDate = string.Format(newToken.ToString());
                    sr.Write(nDate);//开始写入值
                    sr.Close();
                    fs.Close();

                    #endregion
                    ischanage = true;
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            #region 记录下一次更新时间
            if (ischanage)
            {
                string filePath = string.Empty;
                string ExcelPathFolder = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "sysLog";
                filePath = System.IO.Path.Combine(ExcelPathFolder, "TokenEnd.txt");
                FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                StreamWriter sr = new StreamWriter(fs);
                var times = 3; //默认三天更新一次token
                times = int.Parse(ConfigReader.Reader["update"]);
                string nDate = string.Format("{0} 01:00:00", DateTime.Now.AddDays(times).ToString("yyyy-MM-dd"));
                sr.Write(nDate);//开始写入值
                sr.Close();
                fs.Close();
            }
            #endregion

            txt.AddLogMsg(string.Format("更新token任务执行完成，执行结果：{0}", JsonConvert.SerializeObject(rsl)));
        }

        public void auto_saveBar()
        {
            try
            {
                txt.AddLogMsg("开始执行自动提交无效提交条码方法");
                BarBLL barBLL = new BarBLL();
                barBLL.SubmitLostBar();
                txt.AddLogMsg("结束执行自动提交无效提交条码方法");
            }
            catch (Exception ex)
            {
                txt.AddLogMsg("自动任务(auto_saveBar)程序异常：" + ex.Message) ;
            }
        }
        public string GetSysFile(string filename)
        {
            string filePath = string.Empty;
            string ExcelPathFolder = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "sysLog";
            if (!Directory.Exists(ExcelPathFolder))  //如果Folder不存在，则创建
            {
                Directory.CreateDirectory(ExcelPathFolder);
            }
            filePath = System.IO.Path.Combine(ExcelPathFolder, filename + ".txt");
            if (!System.IO.File.Exists(filePath))
            {
                FileStream fs1 = new FileStream(filePath, FileMode.Create, FileAccess.Write);//创建写入文件 

                fs1.Close();
            }
            StreamReader sr = new StreamReader(filePath, Encoding.Default);
            string content;
            content = sr.ReadToEnd();
            sr.Close();
            return content;
        }

       

    }
}
